package net.didactylos.helpline.data;

import java.util.List;

import javax.mail.internet.InternetAddress;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;

@Entity
public class Contact extends EmailContact
{
	@OneToMany(mappedBy="contact")
	@OrderBy("id DESC")
	private List<Conversation> conversations;

	public List<Conversation> getConversations()
	{
		return conversations;
	}

	public void setConversations(List<Conversation> conversations)
	{
		this.conversations = conversations;
	}
	
	public static Contact contactForAddress(InternetAddress from)
	{
		Contact author = new Contact();
		author.setEmailAddress(from.getAddress());
		String name = from.getPersonal();
		if (name != null)
		{
			int split = name.lastIndexOf(' ');
			if (split < 0)
			{
				author.setLastName(name);
				author.setFirstNames("");
			}
			else
			{
				author.setLastName(name.substring(split + 1, name.length()));
				author.setFirstNames(name.substring(0, split));
			}
		}
		return author;
	}

}
